﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;


namespace Talk
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlDataReader data;
                if (Session["UserID"] == null)
                {
                    navbar.Text = "<a href=register.aspx>注册</a> | <a href=login.aspx>登录</a>";
                    cmd.CommandText = "select top(20) MessageID, Content, Username, Time, nPro, nCon from Messages, Users "
                        + "where Users.UserID=Messages.UserID order by MessageID desc";
                    data = cmd.ExecuteReader();
                    while (data.Read())
                    {
                        TableRow tr = new TableRow();
                        TableCell td = new TableCell();
                        td.Text = data["Username"].ToString() + " 在 " + data["Time"].ToString()
                            + " 写道：<br /><pre>" + data["Content"].ToString() + "</pre>"
                            + "<br />赞同(" + data["nPro"].ToString() + ") | 反对(" + data["nCon"].ToString() + ")<hr />";
                        tr.Cells.Add(td);
                        content.Rows.Add(tr);
                    }
                    data.Close();
                }
                else
                {
                    navbar.Text = "<a href=config.aspx>设置</a> | <a href=logout.aspx>退出</a>" +
                        " | 我发布的消息：" + Session["nMessage"] + " | 我关注的用户：" + Session["nFollowing"].ToString() + " | 关注我的用户："
                        + Session["nFollower"].ToString()
                        + " | <a href=follow.aspx>添加关注</a> | <a href=unfollow.aspx>取消关注</a>";
                    cmd.CommandText = "select top(20) MessageID, Content, Username, Time, nPro, nCon"
                        + " from Users, Messages"
                        + " where Users.UserID=Messages.UserID"
                        + " and (Messages.UserID='" + Session["UserID"].ToString() + "'"
                        + " or exists( select * from Follows"
                        + " where Follower='" + Session["UserID"].ToString() + "'"
                        + " and Following=Messages.UserID))"
                        + " order by MessageID desc";
                    data = cmd.ExecuteReader();
                    while (data.Read())
                    {
                        TableRow tr = new TableRow();
                        TableCell td = new TableCell();
                        td.Text = data["Username"].ToString() + " 在 " + data["Time"].ToString()
                            + " 写道：<br /><pre>" + data["Content"].ToString() + "</pre>"
                            + "<br /><a href=vote.aspx?a=pro&i=" + data["MessageID"].ToString() + " >赞同</a>(" + data["nPro"].ToString() + ") | "
                            + "<a href=vote.aspx?a=con&i=" + data["MessageID"].ToString() + " >反对</a>(" + data["nCon"].ToString() + ")<hr />";
                        tr.Cells.Add(td);
                        content.Rows.Add(tr);
                    }
                    data.Close();
                }
                conn.Close();
            }
            catch (System.Exception ex)
            {
                errormsg.Text = ex.Message;
            }
        }

        protected void talksubmit_Click(object sender, EventArgs e)
        {
            errormsg.Text = "";
            if (Session["UserID"] == null)
            {
                errormsg.Text = "请先登录！";
                return;
            }
            if (message.Text.Length < 1)
            {
                errormsg.Text = "内容不能为空！";
                return;
            }
            string msg = message.Text;
            ;
            msg = msg.Replace("&", "&#38;");
            msg = msg.Replace("'", "&#39;");
            msg = msg.Replace("\"", "&#34;");
            msg = msg.Replace("<", "&#60;");
            msg = msg.Replace(">", "&#62;");
            if (msg.Length > 356) msg = msg.Substring(0, 356);
            DateTime now=System.DateTime.Now;
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                string sql = "insert into Messages(UserID, Content, Time) values('"
                    + Session["UserID"].ToString() + "', '" + msg + "', '"
                    + now.ToString() + "'); select ident_current('Messages')";
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader data = cmd.ExecuteReader();
                if (!data.HasRows)
                {
                    errormsg.Text = "消息发布失败！";
                    return;
                }
                data.Read();
                string msgid = data[0].ToString();
                data.Close();
                cmd.CommandText = "update Users set nMessage = nMessage + 1"
                    + " where UserID = '" + Session["UserID"].ToString() + "'";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "select nMessage from Users where UserID = '"
                    + Session["UserID"].ToString() + "'";
                data = cmd.ExecuteReader();
                if(data.HasRows)
                {
                    data.Read();
                    Session["nMessage"] = data[0];
                }
                data.Close();


                // TODO : 添加记录数据到Log表
                cmd.CommandText = "insert into Actions(UserID,What,Time,IP) values("
                    + Session["UserID"].ToString()
                    + ",'" + Session["Username"].ToString() + "发表文章','"
                    + DateTime.Now.ToString() + "','"
                    + Request.UserHostAddress.ToString()
                    + "');"; 
                cmd.ExecuteNonQuery();

                conn.Close();
                Response.Redirect("/index.aspx");
                return;
            }
            catch (System.Exception ex)
            {
                errormsg.Text = ex.Message;
            }
        }
    }
}
